package com.yxuan.springboot.controller;

import com.github.pagehelper.PageInfo;
//import com.sun.org.apache.regexp.internal.RE;
import com.yxuan.springboot.model.Information;
import com.yxuan.springboot.service.CommentService;
import com.yxuan.springboot.service.InformationService;
import com.yxuan.springboot.util.CodeUtil;
import com.yxuan.springboot.util.TencentCOSUploadFileUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
 * 
 * @author zchao
 *   Information控制器
 * @date 2023-05-14 20:40:39
 */
@Slf4j
@Controller
@Api(tags = "资讯表")
@RequestMapping(value = "/information")
public class InformationController extends BaseController<Information>{

    @Autowired
    protected InformationService informationService;
    @Autowired
    protected CommentService commentService;

    /**
      * @className: InformationController.java
      * @methodName: upload
      * @effect: 文件上传腾讯云存储+
      * @author: JingxuanFan
      * @date: 2023/5/15 9:47
      **/
//    name：请求头的名称   value：请求头的描述信息  required：请求头是否必填    dataType：请求头的数据类型   paramType：请求头的类型
    @ApiOperation(value = "上传文件", notes = "将文件上传到腾讯云存储中",httpMethod = "POST")
    @ApiImplicitParams({@ApiImplicitParam(name = "userId", value = "用户登入的Id", required = true, dataType = "string", paramType = "header")})
    @PostMapping("/upload")
    @ResponseBody
    public Map<String, Object> upload(@RequestParam("file") MultipartFile file, HttpServletRequest request){
        Map<String,Object> map = new HashMap<String,Object>();
        try {
            if (null == file) {
               return ResponseMap(CodeUtil.FileNull,"文件为空",null);
            }
//            //在请求头中获取用户登入的Id
//            String id = request.getHeader("userId");
//            //调用工具类中上传文件的方法
//            String filePath = TencentCOSUploadFileUtil.uploadfile(file,id);


            System.out.println(file);
            System.out.println(file.getSize());
            try {
                //1.获取源文件的输入流
                InputStream is = file.getInputStream();
                //2.获取源文件类型，文件后缀名
                String originalFileName = file.getOriginalFilename();
                //3.定义上传后的目标文件名(为了避免文件名称重复，此时使用UUID)
//            String newFileName = UUID.randomUUID().toString()+"."+originalFileName;
                String newFileName = UUID.randomUUID().toString()+"."+originalFileName;
                //4.通过上传路径得到上传的文件夹
                File fileLoad = new File("/root/upload/images");
                //4.1.若目标文件夹不存在，则创建
                if(!fileLoad.exists()){ //判断目标文件夹是否存在
                    fileLoad.mkdirs();//4.2.不存在，则创建文件夹
                }
                //5.根据目标文件夹和目标文件名新建目标文件（上传后的文件）
                File newFile = new File("/root/upload/images",newFileName);  //空的目标文件
                //6.根据目标文件的新建其输出流对象
                FileOutputStream os = new FileOutputStream(newFile);
                //7.完成输入流到输出流的复制
                IOUtils.copy(is,os);
                //8.关闭流(先开后关)
                os.close();
                is.close();

                try {
                    String baseUrl = "https://xc1.haoxnet.com:8098/images/";
                    String fileUrl = newFileName;
                    return ResponseMap(CodeUtil.Susser,null,baseUrl+fileUrl);
                } catch (Exception e) {
                    e.printStackTrace();
                    return null;
                }

            } catch (IOException e) {
                e.printStackTrace();
                return null;
            }


        }catch (Exception e){
            log.error(e.getMessage());
            return ResponseMap(CodeUtil.FileError,e.getMessage(),null);
        }
    }

    /**
      * @className: InformationController.java
      * @methodName: queryInformationId
      * @effect: 手动更新文章数据
      * @author: JingxuanFan
      * @date: 2023/5/19 10:55
      **/
    @ApiOperation(value = "更新文章数据", notes = "查询更新每篇文章的点赞量，收藏量，分享量，阅读量，评论量等",httpMethod = "POST")
    @PostMapping("/queryInformationId")
    @ResponseBody
    public String queryInformationId(){
        try {
            //将所有资讯数据的主键Id,暂存到 List<String>中
            List<String> listId = informationService.queryInformationId();
            for (String s : listId) {
                //根据主键Id，查询到资讯数据
                Information queryInformation = informationService.findTById(s);
                //0点赞，1收藏，2阅读，3分享
                queryInformation.setLikeNumber(informationService.queryoperationNum(s,"0"));
                queryInformation.setCollectionNumber(informationService.queryoperationNum(s,"1"));
                queryInformation.setReadNumber(informationService.queryoperationNum(s,"2"));
                queryInformation.setShareNumber(informationService.queryoperationNum(s,"3"));
                //查询资讯文章的评论数量
                queryInformation.setCommentNumber(commentService.queryCommentNum(s));
                //设置修改时间
                queryInformation.setUpdtime(new Date());
                System.out.println("============================================");
                System.out.println("listId: "+ s);
                System.out.println(queryInformation);
                System.out.println("============================================");
                //修改/更新文章数据
                informationService.upd(queryInformation);
            }
            return "Susser";
        }catch (Exception e){
            log.error(e.getMessage());
            return "Error";
        }
    }

    /**
     * @className: InformationController.java
     * @methodName: pagingQueryInformation
     * @effect: 文章资讯分页查询
     * @author: JingxuanFan
     * @date: 2023/5/28 17:08
    **/
    @ApiOperation(value = "文章分页查询", notes = "查询更新每篇文章所有内容",httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "起始页码", defaultValue = "1", required = true, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "limit", value = "每页记录条数", defaultValue = "10", required = true, dataType = "int", paramType = "query"),
    })
    @GetMapping("/pagingQueryInformation")
    @ResponseBody
   public Map<String, Object> pagingQueryInformation(Integer page, Integer limit){
        try {
            log.info("");
            PageInfo<Information> pageInfoInformation = informationService.pagingQueryInformation(page,limit);
            System.out.println("===========================================");
            System.out.println(pageInfoInformation);
            System.out.println("===========================================");
            return ResponseMap(CodeUtil.Susser,null,pageInfoInformation);
        } catch (Exception e){
            log.error(e.getMessage());
            return ResponseMap(CodeUtil.Error,e.getMessage(),null);
        }

   }

    @ApiOperation(value = "添加数据", notes = "添加数据",httpMethod = "POST")
    @RequestMapping("/save")
    @ResponseBody
    public String saveT(@RequestBody Information information) throws IOException {
        try {
            return baseService.save(information);
        } catch (Exception e) {
            e.printStackTrace();
            return ERROR;
        }
    }

}
